package com.yc.logging.aspect;

import com.yc.common.utils.RequestUtils;
import com.yc.common.utils.ThrowableUtils;
import com.yc.logging.entity.SysOperLog;
import com.yc.logging.service.SysOperLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.junit.jupiter.api.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @Classname LogAspect
 * @Description 日志切面类
 * @Version 1.0.0
 * @Date 2022/8/15 15:31
 * @Created by Mikechen
 */
@Component
@Aspect
@Slf4j
@Order(1)
public class LogAspect {

    private final SysOperLogService logService;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    public LogAspect(SysOperLogService logService) {
        this.logService = logService;
    }


    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.yc.logging.annotation.Log)")
    public void logPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        currentTime.set(System.currentTimeMillis());
        result = joinPoint.proceed();
        LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(System.currentTimeMillis() / 1000, currentTime.get().intValue(), ZoneOffset.ofHours(8));
        SysOperLog log = new SysOperLog("INFO",localDateTime);
        currentTime.remove();
        HttpServletRequest request = RequestUtils.getHttpServletRequest();
        logService.save("username", RequestUtils.getBrowser(request), RequestUtils.getIp(request),joinPoint, log);
        return result;
    }

    /**
     * 配置异常通知
     *
     * @param joinPoint join point for advice
     * @param e exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(System.currentTimeMillis() / 1000, currentTime.get().intValue(), ZoneOffset.ofHours(8));
        SysOperLog log = new SysOperLog("ERROR",localDateTime);
        currentTime.remove();
        log.setExceptionDetail(ThrowableUtils.getStackTrace(e).getBytes());
        HttpServletRequest request = RequestUtils.getHttpServletRequest();
        logService.save("username", RequestUtils.getBrowser(request), RequestUtils.getIp(request),(ProceedingJoinPoint)joinPoint, log);
    }


}
